﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
//using System.Data.SqlClient;
using System.Xml.Linq;

namespace SSRSViewer.Core
{
    public class RdlDataProvider
    {
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(RdlDataProvider));

        public string Name { get; private set; }
        public string CommandText { get; private set; }

        public IDictionary<string, string> ParameterMappings { get; set; }

        public RdlDataProvider(XmlNode datasetNode)
        {
            ParameterMappings = new Dictionary<string, string>();

            try
            {
                Name = datasetNode.Attributes["Name"].Value;

                foreach (XmlNode childNode in datasetNode.ChildNodes)
                {
                    if (childNode.Name == "Query")
                    {

                        foreach (XmlNode queryProps in childNode.ChildNodes)
                        {
                            if (queryProps.Name == "CommandText")
                            {
                                CommandText = queryProps.InnerText;
                            }
                            else if (queryProps.Name == "QueryParameters")
                            {
                                foreach (XmlNode queryparams in queryProps.ChildNodes)
                                {
                                    string sqlParameterName = queryparams.Attributes["Name"].Value;
                                    string parameterName =queryparams.FirstChild.InnerText;
                                    parameterName = parameterName.Substring(parameterName.IndexOf("!") + 1);
                                    parameterName = parameterName.Substring(0, parameterName.IndexOf("."));
                                    ParameterMappings.Add(parameterName, sqlParameterName);
                                }
                            }
                        }

                    }
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                log.Error("", ex);
            }
        }
    }
}
